<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.rules.CreateRules')"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="breadcrumb">
                <a-breadcrumb :routes="routes">
                    <template slot="itemRender" slot-scope="{route, params, routes}">
                        <span v-if="routes.indexOf(route) === routes.length - 1">{{route.breadcrumbName}}</span>
                        <router-link v-else :to="`${route.path}`">{{route.breadcrumbName}}</router-link>
                    </template>
                </a-breadcrumb>
            </div>
            <div class="portlet">
                <a-spin :spinning="loading" size="large" :tip="$t('pro.public.loading')">
                    <a-form class="conditions grid" :form="form" layout="vertical">
                        <div class="grid-item">
                            <div class="grid-item-main">
                                <a-form-item :label="$t('pro.EditRules.RulesName')">
                                    <a-input
                                            :placeholder="$t('pro.EditRules.RulesTip')"
                                            v-decorator="[
                                              'name',
                                              {
                                                rules: [{
                                                  required: true, message: $t('pro.EditRules.RulesNameMess')
                                                }],
                                              }
                                              ]"
                                    />
                                </a-form-item>
                                <a-form-item :label="$t('pro.EditRules.Rtbspecification')">
                                    <a-select
                                            :placeholder="$t('pro.EditRules.OptionMess')"
                                            :filterOption="filterOption"
                                            allowClear
                                            showSearch
                                            @inputKeydown="handleCreateExchange($event)"
                                            @search="handleSearch($event)"
                                            style="width: 100%"
                                            v-decorator="['rtbspecification',{
                                                rules: [{
                                                  required: true, message: $t('pro.EditRules.RtbspecificationMess')
                                                }],
                                              }]"
                                    >
                                        <a-select-option
                                                v-for="exchange in exchangeList"
                                                :key="exchange.id"
                                                :value="exchange.rtbspecification"
                                        >{{ exchange.rtbspecification}}</a-select-option>
                                    </a-select>
                                </a-form-item>
                                <a-form-item :label="$t('pro.EditRules.Operator')">
                                    <a-select
                                            :placeholder="$t('pro.EditRules.OptionMess')"
                                            style="width: 100%"
                                            v-decorator="['operator']"
                                    >
                                        <a-select-option
                                                v-for="Operator in OperatorArr"
                                                :key="Operator.key"
                                                :value="Operator.key"
                                        >{{ Operator.name}}</a-select-option>
                                    </a-select>
                                </a-form-item>
                                <a-form-item :label="$t('pro.EditRules.OperandType')">
                                    <a-select
                                            :placeholder="$t('pro.EditRules.OptionMess')"
                                            style="width: 100%"
                                            v-decorator="['operandType']"
                                    >
                                        <a-select-option v-for="operandType in operandTypeArr"
                                                         :key="operandType.key"
                                                         :value="operandType.key">
                                            {{operandType.name}}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </div>
                        </div>
                        <!-- 第二瀑布 -->
                        <div class="grid-item">
                            <div class="grid-item-main">
                                <!-- 匹配值数据类型 -->
                                <a-form-item :label="$t('pro.EditRules.OperandOrdinal')">
                                    <a-select
                                            :placeholder="$t('pro.EditRules.OptionMess')"
                                            style="width: 100%"
                                            v-decorator="['operandOrdinal']"
                                    >
                                        <a-select-option v-for="operandOrdinal in operandOrdinalArr"
                                             :key="operandOrdinal.key"
                                             :value="operandOrdinal.key">
                                            {{operandOrdinal.name}}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                                <!-- 配值 -->
                                <a-form-item :label="$t('pro.EditRules.OperandValue')">
                                    <a-input
                                            :placeholder="$t('pro.EditRules.OperandTip')"
                                            v-decorator="['operand']"/>
                                </a-form-item>
                                <!--<a-form-item :label="$t('pro.EditRules.UseSetOperand')">
                                    <a-select
                                            allowClear
                                            showSearch
                                            style="width: 100%"
                                            v-decorator="['operandListId']"
                                    >
                                        <a-select-option key="1">domains</a-select-option>
                                    </a-select>
                                </a-form-item>-->
                            </div>
                        </div>
                        <div class="grid-item">
                            <div class="grid-item-main">
                                <a-form-item :label="$t('pro.EditRules.RTBRequired')">
                                    <a-checkbox
                                            style="width: 100%;"
                                            v-decorator="['rtbRequired',{ valuePropName: 'checked' }]"
                                    >
                                    </a-checkbox>
                                </a-form-item>
                                <a-form-item :label="$t('pro.EditRules.Description')">
                                    <a-input
                                            :placeholder="$t('pro.EditRules.textTip')"
                                            type='textarea'
                                            :rows="3"
                                            v-decorator="['description']"
                                    />
                                </a-form-item>
                            </div>
                        </div>
                        <!-- Submit Button   -->
                        <div class="grid-item">
                            <a-form-item>
                                <a-button
                                    type="primary"
                                    html-type="submit"
                                    @click="handleSubmit($event)"
                                    v-text="submitText"
                                ></a-button>
                            </a-form-item>
                        </div>
                    </a-form>
                </a-spin>
            </div>
        </div>
    </div>

</template>

<script>
    import {AddRule,getRules,updateRule} from "@/api/rule-controller";
    import {getExchangeList} from "@/api/pulldown-data";
    export default {
        data(){
          return {
              loading:false,
              form: this.$form.createForm(this),
              exchangeList: [],
              CustomValue: null,
          }
        },
        computed:{
            OperatorArr(){
                return this.$t('pro.EditRules.OperatorArr')
            },
            operandTypeArr(){
                return this.$t('pro.EditRules.operandType')
            },
            operandOrdinalArr(){
                return this.$t('pro.EditRules.operandOrdinal')
            },
            routes(){
                const routes = [
                    {
                        path: "/admin/CampaignsRules",
                        breadcrumbName: this.$t('pro.rules.Rules')
                    },
                    {
                        path: "second",
                        breadcrumbName: this.$t('pro.rules.CreateRules')
                    }
                ]
                return routes
            },
            rulesId(){
                return this.$route.params.id;
            },
            submitText(){
                return this.rulesId != null?this.$t('pro.EditRules.SaveRules'):this.$t('pro.rules.CreateRules')
            },
        },
        methods:{
            //创建规则的提交事件
            handleSubmit(e) {
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        const rulesId = this.rulesId;
                        if(rulesId == null){
                            this.loading = !this.loading;//开启动画
                            AddRule(values).then(res=>{
                                if (res.data.code == '200'){
                                    this.$message.success(this.$t('pro.createFilterList.createSuccess')).then(()=>{
                                        this.$router.push({
                                            path:'/admin/CampaignsRules'
                                        })
                                    })
                                }
                            }).finally(()=>{
                                this.loading = !this.loading;//关闭动画
                            })
                        }else {
                            this.loading = !this.loading;
                            values.id = rulesId;
                            updateRule(values).then(res=>{
                                if (res.data.code == 200){
                                    this.$message.success(this.$t('pro.EditRules.EditSuccess')).then(()=>{
                                        this.$router.push({
                                            path:'/admin/CampaignsRules'
                                        })
                                    })
                                }
                            }).catch(err =>{

                            }).finally(()=>{
                                setTimeout(()=>{
                                    this.loading = !this.loading;//关闭动画
                                },2000)

                            })
                        }
                    }
                });
            },
            filterOption(input, option){
                return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            },
            handleSearch(e){
                this.CustomValue = e
            },
            //回车创建新的列表
            handleCreateExchange(e){
                if(e.keyCode == 13){
                    let value = this.CustomValue
                    let isValue = this.exchangeList.every(item =>{
                        return item.rtbspecification !== value
                    })
                    if (isValue){
                        this.exchangeList.push({
                            id:this.exchangeList.length,
                            rtbspecification:value
                        })
                    }
                }
            },
        },
        created(){
            if (this.rulesId != null) {
                this.routes[1].breadcrumbName = this.$t('pro.rules.EditRules')
                this.loading = !this.loading;//开启加载动画
                let parameter = "/" + this.rulesId;
                getRules(parameter).then(res => {
                    this.form = this.$form.createForm(this, {
                        // 当Form.Item子节点的值发生改变时触发，可以把对应的值转存到 Redux store
                        //onFieldsChange: (_, changedFields) => {},
                        // 把 props 转为对应的值，可用于把 Redux store 中的值读出,可以在此给form赋值
                        mapPropsToFields: () => {
                            const obj = res.data.data;
                            if (!obj) return;
                            let data = {};
                            for (let [key, value] of Object.entries(obj)) {
                                data[key] = this.$form.createFormField({ value });
                            }
                            return data;
                        },
                        // 任一表单域的值发生改变时的回调
                        onValuesChange: (_, values) => {}
                    })
                }).finally(() => {
                    this.loading = !this.loading;//关闭动画
                })
            }

        },
        beforeMount() {
            getExchangeList().then(res =>{
                this.exchangeList = res.data.data
            })
        },
    }
</script>

<style scoped>
    .conditions > div:nth-child(3) .grid-item-title {
        border-bottom: 1px solid #c2cad8;
    }
</style>
